package cn.com.duiba.millionaire.center.biz.service.impl;

import cn.com.duiba.millionaire.center.api.cache.UserAnswerList;
import cn.com.duiba.millionaire.center.api.msg.SubmitAnswerMsg;
import cn.com.duiba.millionaire.center.biz.service.UserSelectionInfoService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zzy on 2018/1/23.
 */
@Service
public class UserSelectionInfoServiceImpl implements UserSelectionInfoService {
    @Resource(name = "redisTemplate")
    private RedisTemplate<String, UserAnswerList> redisTemplate;

    @Override
    public void batchUpdate(List<SubmitAnswerMsg> msgs, boolean isSubmittedAnswer) {
        if (CollectionUtils.isEmpty(msgs)) {
            return;
        }
        List<String> keys = Lists.newArrayList();
        Map<String, SubmitAnswerMsg> map = Maps.newHashMap();
        for (SubmitAnswerMsg msg : msgs) {
            String key = UserAnswerList.generateCacheKey(msg.getActivityId(), msg.getConsumerId());
            keys.add(key);
            map.put(key, msg);
        }
        List<UserAnswerList> userAnswerLists = new ArrayList<>();
        List<UserAnswerList> userAnswers = redisTemplate.opsForValue().multiGet(keys);
        for (int i = 0; i < userAnswers.size(); i++) {
            UserAnswerList userAnswer = userAnswers.get(i);
            SubmitAnswerMsg msg = map.get(keys.get(i));
            if (null == userAnswer) {
                userAnswer = new UserAnswerList();
                userAnswer.setActivityId(msg.getActivityId());
                userAnswer.setConsumerId(msg.getConsumerId());
                userAnswer.setUserAnswerMap(Maps.newHashMap());
            }
            // 未提交的请求修改为未提交答案标记
            String userSelect = !isSubmittedAnswer ? UserAnswerList.UNSUBMIT_ANSWER : msg.getUserAnswer();
            userAnswer.getUserAnswerMap().put(msg.getQuestionIndex(), userSelect);
            userAnswerLists.add(userAnswer);
        }

        redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            RedisSerializer<Object> keyS = (RedisSerializer<Object>) redisTemplate.getKeySerializer();
            RedisSerializer<Object> valueS = (RedisSerializer<Object>) redisTemplate.getValueSerializer();
            for (UserAnswerList userAnswerList : userAnswerLists) {
                byte[] keyByte = keyS.serialize(UserAnswerList.generateCacheKey(userAnswerList.getActivityId(), userAnswerList.getConsumerId()));
                connection.set(keyByte, valueS.serialize(userAnswerList));
                connection.expire(keyByte,86400);
            }
            return null;
        });
    }

    @Override
    public UserAnswerList findUserAnswer(Long activityId, Long consumerId) {
        return redisTemplate.opsForValue().get(UserAnswerList.generateCacheKey(activityId, consumerId));
    }
}
